package com.fingard.dsp.bank.directbank.boc01;

import java.io.File;
import java.util.Date;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.ICurrencyExchange;
import com.fingard.dsp.bank.reqrespobj.currencyexchange.ReqExchange;
import com.fingard.dsp.bank.reqrespobj.currencyexchange.ReqQryExchange;
import com.fingard.dsp.bank.reqrespobj.currencyexchange.RetAtsExchange;
import com.fingard.dsp.bank.reqrespobj.currencyexchange.detail.RetAtsExchangeDetail;
import com.fingard.dsp.bank.reqrespobj.foreigncurrsingle.RetAtsForeignCurrSingle;
import com.fingard.dsp.bank.reqrespobj.foreigncurrsingle.detail.RetAtsForeignCurrPayDetail;
import com.fingard.io.FileHelper;
import com.fingard.net.ConnState;
import com.fingard.text.StringHelper;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;


/**
 * Created by Lewis on 2017/9/23.
 */
public class BOC01PurchaseExchange extends BOC01Base implements ICurrencyExchange {
    //银行不支持
    @Override
    public RetAtsExchange exchangePay(ReqExchange exchangePay) throws Exception {
        //返回ATS的对象
        RetAtsExchange retAts = new RetAtsExchange(exchangePay.reqHeader);
        RetAtsExchangeDetail retDetail = new RetAtsExchangeDetail();
        BOC01Header bankHeader = new BOC01Header();
        bankHeader.trncod = "b2e0225";//交易代码
        bankHeader.trnid = getQryTransID();//报文编号 字母数字串 0-12位
        XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
        //写入通用的头部节点
        //Date tmpDateNow = new Date();
        writeCommonHeader(xmlWriter, bankHeader);
        xmlWriter.writeStartElement("trn-" + bankHeader.trncod + "-rq");
        XElement tmpXElement = new XElement(bankHeader.trncod + "-rq", "");
        tmpXElement.addChild(new XElement("unitname", exchangePay.singleDetail.payName));//need 申请单位名称
        tmpXElement.addChild(new XElement("accountnum", exchangePay.singleDetail.payAct));
        tmpXElement.addChild(new XElement("accountname", exchangePay.singleDetail.payName));
        tmpXElement.addChild(new XElement("accountibk", ""));//购汇账户联行号
        //012|GBP 英镑,013|HKD 港元,014|USD 美元,015|CHF 瑞士法郎,018|SGD 新加坡元,021|SEK 瑞典克郎,022|DKK 丹麦克郎,023|NOK 挪威克郎,027|JPY 日元,
        //028|CAD 加拿 大元, 029|AUD 澳大 利亚元, 038|EUR 欧元, 081|MOP 澳门 元, 082|PHP 菲律 宾比索, 084|THB 泰国 铢, 087|NZD 新西 兰元, 088|KRW 韩元
        tmpXElement.addChild(new XElement("currency", this.convertCurToBank(exchangePay.singleDetail.recCur)));//购汇币种 为收方币种
        tmpXElement.addChild(new XElement("amount", exchangePay.singleDetail.payAmount));
        tmpXElement.addChild(new XElement("recnum", exchangePay.singleDetail.recAct));
        tmpXElement.addChild(new XElement("recname", exchangePay.singleDetail.recName));
        tmpXElement.addChild(new XElement("recibk", ""));//可空 收款账户联行号
        tmpXElement.addChild(new XElement("furinfo", exchangePay.singleDetail.purpose));//备注
        tmpXElement.addChild(new XElement("contactname", exchangePay.singleDetail.contactPerson));
        tmpXElement.addChild(new XElement("contactphone", exchangePay.singleDetail.contactNum));
        tmpXElement.addChild(new XElement("insid", exchangePay.singleDetail.askNumber));
        //用途 321,运输322,旅游323,金融和保险服务324,专有权利使用费和特许费325,咨询服务326,其他服务331,职工报酬和赡家款332,投资收益333,其他经常转移
        tmpXElement.addChild(new XElement("purpose", "326"));//非空数字
        tmpXElement.addChild(new XElement("orgtype","1".equals(exchangePay.singleDetail.payOrgType)?"Z":"W"));//Z-中资机构 W-外资机构
        tmpXElement.addChild(new XElement("cliorg", exchangePay.singleDetail.payOrgCode));//need组织机构代码
        tmpXElement.addChild(new XElement("trankind", "922090"));//need交易编码
        tmpXElement.addChild(new XElement("cusref", exchangePay.singleDetail.businessNum));//可空 外汇局批件号/备案表号/业务编号
        tmpXElement.addChild(new XElement("brsign", "2"));//可空 钞汇标示 1-钞户 2-汇户 默认为2
        nodeAnalysis(exchangePay.singleDetail.srcXElement, tmpXElement, getCharset());
        xmlWriter.writeXElement(tmpXElement);
        xmlWriter.writeEndDocument();//写入报文完成
        String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());//发送银行
        /*tmpStrRet[0]="";
        tmpStrRet[1]="<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
                "<bocb2e version=\"120\" locale=\"zh_CN\">\n" +
                "\t<head>\n" +
                "\t\t<termid>E022011099095</termid>\n" +
                "\t\t<trnid>04051003129</trnid>\n" +
                "\t\t<custid>10095720</custid>\n" +
                "\t\t<cusopr>b2egaoy</cusopr>\n" +
                "\t\t<trncod>b2e0225</trncod>\n" +
                "\t\t<token>24BDF753CF83EE57B25BD3924189D5F7</token>\n" +
                "\t</head>\n" +
                "\t<trans>\n" +
                "\t\t<trn-b2e0225-rs>\n" +
                "\t\t<status>\n"+
                "\t\t<rspcod>B001</rspcod>\n"+
                "\t\t<rspmsg>模拟返回成功</rspmsg>\n"+
                "\t\t</status>\n"+
                "\t\t\t<b2e0225-rs>\n" +
                "\t\t\t\t<status>\n\n" +
                "\t\t\t\t<rspcod>B001</rspcod>\n\n" +
                "\t\t\t\t<rspmsg>购汇模拟返回成功</rspmsg>\n\n" +
                "\t\t\t\t</status>\n\n" +
                "\t\t\t\t<insid>"+exchangePay.singleDetail.askNumber+"</insid>\n" +
                "\t\t\t\t<obssid></obssid>\n" +
                "\t\t\t\t<fstamount>"+exchangePay.singleDetail.payAmount+"</fstamount>\n" +
                "\t\t\t\t<rate>"+exchangePay.singleDetail.payAmount+"</rate>\n" +
                "\t\t\t</b2e0225-rs>\n" +
                "\t\t</trn-b2e0225-rs>\n" +
                "\t</trans>\n" +
                "</bocb2e> ";*/
        if (tmpStrRet[0].length() == 0) {
            StringBuilder tmpSbMsg = new StringBuilder();
            //解析银行返回
            XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
            if (tmpBkReader != null) {
                String tmprspcod = tmpBkReader.getFirstText("/bocb2e/trans/trn-" + bankHeader.trncod + "-rs/status/rspcod");
                String tmprspmsg = tmpBkReader.getFirstText("/bocb2e/trans/trn-" + bankHeader.trncod + "-rs/status/rspmsg");
                if (isActiveRetCode(tmprspcod)) {
                    if (tmpBkReader.read("/bocb2e/trans/trn-" + bankHeader.trncod + "-rs/" + bankHeader.trncod + "-rs")) {
                        retDetail.respCode = "0";
                        retDetail.transState = tmprspcod+"+"+tmpBkReader.readedXElement.getSingleText("status/rspcod");
                        retDetail.payInfoCode = retDetail.transState;
                        retDetail.respInfo = tmpBkReader.readedXElement.getSingleText("status/rspmsg");
                        retDetail.reqSeqID = exchangePay.singleDetail.askNumber;
                        String insid = tmpBkReader.readedXElement.getSingleText("insid");
                        String obssid = tmpBkReader.readedXElement.getSingleText("obssid");
                        String filename = getBankConfig().getValueAsString("saveDir")+ File.separator+ Format.Date8Format.format(new Date())
                                +File.separator+exchangePay.singleDetail.askNumber+".txt";
                        FileHelper.writeFile(filename,insid+"|"+obssid+"|"+bankHeader.trncod,"gbk");
                    } else {
                        retDetail.respCode = "0";
                        retDetail.transState = tmprspcod;
                        retDetail.payInfoCode = tmprspcod;
                        retDetail.respInfo = tmprspmsg;
                        retDetail.reqSeqID = exchangePay.singleDetail.askNumber;
                    }
                } else {
                    retDetail.respCode = "-1";
                    retDetail.transState = tmprspcod;
                    retDetail.respInfo = tmprspmsg;
                }
            } else {
                retDetail.respCode = "-1";
                retDetail.respInfo = tmpSbMsg.toString();
            }
        } else if (tmpStrRet[0].equals(ConnState.FAIL)) {
            retDetail.respCode = "0";
            retDetail.respInfo = tmpStrRet[1];
            retDetail.reqSeqID = exchangePay.singleDetail.askNumber;
            retDetail.transState = PaymentState.FAIL_Payment;
            retDetail.payInfoCode = tmpStrRet[0];
        } else {
            retDetail.respCode = "-1";
            retDetail.respInfo = tmpStrRet[1];
        }
        if (retDetail.respCode.equals("-1") && StringHelper.isNullOrEmpty(retDetail.reqSeqID)) {
            retDetail.reqSeqID = exchangePay.singleDetail.askNumber;
        }
        retAts.writeRetDetail(retDetail);
        return retAts;
    }
    //银行不支持 银行无接口
    @Override
    public RetAtsExchange qryExchangePay(ReqQryExchange exchangeQry) throws Exception {
        RetAtsExchange retAts = new RetAtsExchange(exchangeQry.reqHeader);
        RetAtsExchangeDetail detail = new RetAtsExchangeDetail();
        String filename = getBankConfig().getValueAsString("saveDir")+ File.separator+exchangeQry.bgnDate.substring(0,10).replaceAll("-","")
                +File.separator+exchangeQry.askNumber+".txt";
        try {
            if (!FileHelper.existFile(filename)) {
                throw new Exception("不存在,请和银行确认该交易!");
            }
            //insid|obssid|交易码
            String context = FileHelper.readFileText(filename, "gbk");
            String[] reqIds = context.split("\\|");
            if (reqIds.length == 3) {
                XmlTextWriter xmlTextWriter = new XmlTextWriter();
                BOC01Header header = new BOC01Header();
                header.trncod = "b2e0007";
                header.trnid = getQryTransID();
                writeCommonHeader(xmlTextWriter, header);
                xmlTextWriter.writeStartElement("trn-b2e0007-rq");
                xmlTextWriter.writeStartElement("b2e0007-rq");
                xmlTextWriter.writeElementString("insid",reqIds[0]);
                xmlTextWriter.writeElementString("obssid",reqIds[1]);
                xmlTextWriter.writeEndDocument();
                String[] tmpStrRet = sendToBank(xmlTextWriter.toXmlString());//发送银行
                if (tmpStrRet[0].length() == 0) {
                    StringBuilder tmpSbMsg = new StringBuilder();
                    //解析银行返回
                    XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                    if (tmpBkReader != null) {
                        String tmprspcod = tmpBkReader.getFirstText("/bocb2e/trans/trn-b2e0007-rs/status/rspcod");
                        String tmprspmsg = tmpBkReader.getFirstText("/bocb2e/trans/trn-b2e0007-rs/status/rspmsg");
                        if (isActiveRetCode(tmprspcod)) {
                            //retDetail.respCode = "0";
                            //retDetail.respInfo = tmpRetMsg;
                            //retDetail.reqSeqID = tmpBkReader.getFirstText("/CMS/eb/pub/fSeqno");
                            if (tmpBkReader.read("/bocb2e/trans/trn-b2e0007-rs/b2e0007-rs")) {
                                detail.respCode = "0";
                                detail.transState =tmprspcod +"+"+ tmpBkReader.readedXElement.getSingleText("status/rspcod");
                                detail.payInfoCode = detail.transState;
                                detail.respInfo = tmpBkReader.readedXElement.getSingleText("status/rspmsg");
                            } else {
                                detail.respCode = "0";
                                detail.transState = tmprspcod;
                                detail.payInfoCode = tmprspcod;
                                detail.respInfo = tmprspmsg;
                            }
                        } else {
                            detail.respCode = "-1";
                            detail.respInfo = tmprspmsg;
                        }
                    } else {
                        detail.respCode = "-1";
                        detail.respInfo = tmpSbMsg.toString();
                    }
                } else {
                    detail.respCode = "-1";
                    detail.respInfo = tmpStrRet[1];
                }
            }else{
                throw new Exception("存放银行的流水号文件内容异常");
            }
        }catch (Exception ex){
            detail.respCode ="-1";
            detail.respInfo = ex.getMessage();
            ex.printStackTrace();
        }
        retAts.writeRetDetail(detail);
        return retAts;
    }
}
